# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 15:32:21 2018

@author: Luther
"""

from aip import AipNlp
import sim
import os
import time
import pandas as pd
""" 你的 APPID AK SK """
APP_ID = '10771642'
API_KEY = '7QKEGf47U1trhYptTB3bM4gP'
SECRET_KEY = 'sdDSGirKljr4ijyRGYFOgP4VEtoP7W6a'

client = AipNlp(APP_ID, API_KEY, SECRET_KEY)

title = "核心竞争力分析"


def getkw(title, content):
    ret = ''
    try:
        j = client.keyword(title, content[:10000])
    except:
        j = {}
    try:
        for i in j['items']:
            ret = ret + i['tag'] + '/' + str(i['score']) + '/'
    except KeyError:
        pass
    return ret[:-1]


# getkw(title, content)
def compute(path, ret_path):

    file_list = [
        x for x in os.listdir(path) if os.path.splitext(x)[-1] == '.txt'
    ]
    print("{:}个待检索文件读取成功!".format(len(file_list)))

    #df = sim.getcode(file_list)
    df = pd.read_csv(r'C:\users\luther\desktop\miss.csv')
    ret = []
    start_time = time.time()
    for i in range(len(df)):
        code = (6 - len(str(int(df.stkcd[i])))) * '0' + str(int(df.stkcd[i]))
        year = df.year[i]
        file = '{}-{}.txt'.format(year, code)
        content = sim.readtext(path, file)
        ret_each = getkw(title, content)
        ret.append(ret_each)
        end_time = time.time()
        remain_time = (end_time - start_time) / (i + 1) * (len(df) - (i + 1))
        print(
            "\r{:>6.2f}% Done, Time Remained: {:04}:{:02}:{:02}".format(
                (i + 1) * 100 / len(df), int(remain_time // 3600),
                int(remain_time // 60 % 60), int(remain_time % 60)),
            end="")

    df['kw'] = ret
    df.to_csv(ret_path, index=False)
